const express = require('express');
const path = require('path');
const fs = require('fs').promises;
const sharp = require('sharp');
const { v4: uuidv4 } = require('uuid');
const { auth } = require('../middleware/auth');
const { getConnection } = require('../config/database');
const { removeWatermark } = require('../services/watermarkRemover');

const router = express.Router();

// 开始处理任务
router.post('/start/:taskId', auth, async (req, res) => {
  try {
    const { taskId } = req.params;
    const { mode = 'standard', regions = [] } = req.body;
    
    const connection = await getConnection();

    // 获取任务信息
    const [tasks] = await connection.execute(
      'SELECT * FROM tasks WHERE id = ? AND user_id = ?',
      [taskId, req.user.id]
    );

    if (tasks.length === 0) {
      return res.status(404).json({ error: '任务不存在' });
    }

    const task = tasks[0];

    if (task.status !== 'pending') {
      return res.status(400).json({ error: '任务状态不允许处理' });
    }

    // 更新任务状态为处理中
    await connection.execute(
      'UPDATE tasks SET status = ?, progress = ? WHERE id = ?',
      ['processing', 0, taskId]
    );

    // 异步处理任务
    processTask(taskId, task, mode, regions, req.user.id);

    res.json({
      message: '任务开始处理',
      taskId,
      status: 'processing'
    });
  } catch (error) {
    console.error('开始处理任务错误:', error);
    res.status(500).json({ error: '开始处理失败' });
  }
});

// 异步处理任务
async function processTask(taskId, task, mode, regions, userId) {
  const connection = await getConnection();
  const uploadDir = process.env.UPLOAD_PATH || './uploads';
  
  try {
    // 更新进度为10%
    await connection.execute(
      'UPDATE tasks SET progress = ? WHERE id = ?',
      [10, taskId]
    );

    const inputPath = path.join(uploadDir, task.original_file);
    const outputFileName = `processed-${uuidv4()}-${Date.now()}${path.extname(task.original_file)}`;
    const outputPath = path.join(uploadDir, outputFileName);

    // 更新进度为30%
    await connection.execute(
      'UPDATE tasks SET progress = ? WHERE id = ?',
      [30, taskId]
    );

    let result;
    if (task.task_type === 'image') {
      result = await processImage(inputPath, outputPath, mode, regions);
    } else {
      result = await processVideo(inputPath, outputPath, mode, regions);
    }

    // 更新进度为90%
    await connection.execute(
      'UPDATE tasks SET progress = ? WHERE id = ?',
      [90, taskId]
    );

    if (result.success) {
      // 更新任务为完成状态
      await connection.execute(
        'UPDATE tasks SET status = ?, processed_file = ?, progress = ? WHERE id = ?',
        ['completed', outputFileName, 100, taskId]
      );

      // 记录处理历史
      await connection.execute(
        'INSERT INTO processing_history (user_id, task_id, file_name, file_size, processing_time) VALUES (?, ?, ?, ?, ?)',
        [userId, taskId, task.original_file, result.fileSize, result.processingTime]
      );

      // 更新用户使用量
      await connection.execute(
        'UPDATE users SET monthly_usage = monthly_usage + 1 WHERE id = ?',
        [userId]
      );

      console.log(`✅ 任务 ${taskId} 处理完成`);
    } else {
      throw new Error(result.error);
    }
  } catch (error) {
    console.error(`❌ 任务 ${taskId} 处理失败:`, error);
    
    // 更新任务为失败状态
    await connection.execute(
      'UPDATE tasks SET status = ?, error_message = ?, progress = ? WHERE id = ?',
      ['failed', error.message, 0, taskId]
    );
  }
}

// 处理图片
async function processImage(inputPath, outputPath, mode, regions) {
  const startTime = Date.now();
  
  try {
    // 这里应该调用实际的AI去水印算法
    // 目前使用简单的图像处理作为示例
    const image = sharp(inputPath);
    
    // 根据模式调整处理参数
    let processedImage = image;
    
    if (mode === 'fast') {
      // 快速模式：简单的模糊处理
      processedImage = image.blur(2);
    } else if (mode === 'standard') {
      // 标准模式：中等质量处理
      processedImage = image.blur(1);
    } else if (mode === 'fine') {
      // 精细模式：高质量处理
      processedImage = image.sharpen();
    }

    // 如果有指定区域，进行区域处理
    if (regions && regions.length > 0) {
      // 这里应该实现区域特定的处理逻辑
      console.log('处理指定区域:', regions);
    }

    // 保存处理后的图片
    await processedImage.toFile(outputPath);
    
    // 获取文件大小
    const stats = await fs.stat(outputPath);
    
    return {
      success: true,
      fileSize: stats.size,
      processingTime: Date.now() - startTime
    };
  } catch (error) {
    return {
      success: false,
      error: error.message
    };
  }
}

// 处理视频
async function processVideo(inputPath, outputPath, mode, regions) {
  const startTime = Date.now();
  
  try {
    // 这里应该调用实际的视频去水印算法
    // 目前使用简单的视频复制作为示例
    await fs.copyFile(inputPath, outputPath);
    
    // 获取文件大小
    const stats = await fs.stat(outputPath);
    
    return {
      success: true,
      fileSize: stats.size,
      processingTime: Date.now() - startTime
    };
  } catch (error) {
    return {
      success: false,
      error: error.message
    };
  }
}

// 获取任务状态
router.get('/status/:taskId', auth, async (req, res) => {
  try {
    const { taskId } = req.params;
    const connection = await getConnection();

    const [tasks] = await connection.execute(
      'SELECT id, status, progress, processed_file, error_message, created_at FROM tasks WHERE id = ? AND user_id = ?',
      [taskId, req.user.id]
    );

    if (tasks.length === 0) {
      return res.status(404).json({ error: '任务不存在' });
    }

    const task = tasks[0];
    
    res.json({
      taskId: task.id,
      status: task.status,
      progress: task.progress,
      processedFile: task.processed_file ? `/uploads/${task.processed_file}` : null,
      errorMessage: task.error_message,
      createdAt: task.created_at
    });
  } catch (error) {
    console.error('获取任务状态错误:', error);
    res.status(500).json({ error: '获取任务状态失败' });
  }
});

// 获取用户所有任务
router.get('/tasks', auth, async (req, res) => {
  try {
    const { page = 1, limit = 10, status } = req.query;
    const offset = (page - 1) * limit;
    
    const connection = await getConnection();
    
    let query = 'SELECT * FROM tasks WHERE user_id = ?';
    let params = [req.user.id];
    
    if (status) {
      query += ' AND status = ?';
      params.push(status);
    }
    
    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), offset);

    const [tasks] = await connection.execute(query, params);
    
    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM tasks WHERE user_id = ?';
    let countParams = [req.user.id];
    
    if (status) {
      countQuery += ' AND status = ?';
      countParams.push(status);
    }
    
    const [countResult] = await connection.execute(countQuery, countParams);
    const total = countResult[0].total;

    res.json({
      tasks: tasks.map(task => ({
        id: task.id,
        taskType: task.task_type,
        status: task.status,
        progress: task.progress,
        originalFile: `/uploads/${task.original_file}`,
        processedFile: task.processed_file ? `/uploads/${task.processed_file}` : null,
        errorMessage: task.error_message,
        createdAt: task.created_at
      })),
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取任务列表错误:', error);
    res.status(500).json({ error: '获取任务列表失败' });
  }
});

// 取消任务
router.post('/cancel/:taskId', auth, async (req, res) => {
  try {
    const { taskId } = req.params;
    const connection = await getConnection();

    const [tasks] = await connection.execute(
      'SELECT status FROM tasks WHERE id = ? AND user_id = ?',
      [taskId, req.user.id]
    );

    if (tasks.length === 0) {
      return res.status(404).json({ error: '任务不存在' });
    }

    if (tasks[0].status !== 'processing') {
      return res.status(400).json({ error: '只能取消正在处理的任务' });
    }

    // 更新任务状态为失败
    await connection.execute(
      'UPDATE tasks SET status = ?, error_message = ? WHERE id = ?',
      ['failed', '用户取消', taskId]
    );

    res.json({ message: '任务已取消' });
  } catch (error) {
    console.error('取消任务错误:', error);
    res.status(500).json({ error: '取消任务失败' });
  }
});

module.exports = router; 